<?php
/**
 * beimuaihui System
 * Copyright(c) 2011-2020 beimuaihui.
 * @license    http://www.gnu.org/licenses/gpl.html     This software Under GPL V3 License 
 * beimuaihui@gmail.com
 * http://code.google.com/p/beimuaihui/
 * $Id: UserinfoController.php 465 2012-02-12 05:33:23Z beimuaihui $
 */



class Mall_UserinfoController extends Baogg_Controller_Action {

	function init() 
	{
		Zend_Loader::loadClass ( 'UserInfo' );
		
		$model_id=$this->getRequest()->getParam('model_id',0);
		$this->userinfo = new UserInfo ($model_id);
		
		$this->model=new ModelTable($model_id);
		
		Baogg_Language::loadFile($this->model->getName());
	}

	/**
	 * The default action
	 */
	public function listAction() {
		global $LANG;
		
		Zend_Loader::loadClass('User');
		$user=new User();
		
		$params=$this->getRequest()->getParams();
		$form_url=$params;
		$model_id=$this->getRequest()->getParam('model_id');
		$user_id=$this->getRequest()->getParam('user_id');
		//$user_group_id=$_SESSION['admin']['user_group_role']['user_group_id']?$_SESSION['admin']['user_group_role']['user_group_id']:$_SESSION['admin']['user']['user_id'];
		//		echo '<pre>';print_r($_REQUEST);exit;
		
		Zend_Loader::loadClass('ModelField');
		$modelField=new ModelField();
		$rs=$modelField->getList(array("model_id"=>$model_id,"state"=>1),array("sort"=>"ordering","dir"=>"asc"));
		
		Zend_Loader::loadClass("Baogg_View_Extgrid");
		
		$cm=array();
		foreach((array)$rs as $v){
			if(in_array($v['field_view'],array('combo','radiogroup','checkboxgroup'))){
				$cm[$v['field_name']]=array("hidden"=>true);
				$cm[$v['field_name'].'2']=array("header"=>$v['show_name']);
				continue;
			}
			if($v['field_view']=='fileuploadfield'){
				$cm[$v['field_name'].'2']=array("header"=>$v['show_name']);
				continue;
			}
			$cm[$v['field_name']]=array("header"=>$v['show_name']);
			if($v['field_key']=='PRI'){
				$cm[$v['field_name']]['cmType']=Baogg_View_Extgrid::CMTYPE_PK;
			}
			if(!$v['is_basic'] || $v['field_view']=='hidden'){
				$cm[$v['field_name']]['hidden']=true;
			}
			
		}
		$form_url['action']="data";
		$grid=new Baogg_View_Extgrid($form_url, $cm);
		
		$grid->setSelectionModel(true);
		$grid->setRowNumberer(true);
		$grid->addExistButtons(array('add','remove','query'),array('edit','delete'));
		
		
		$Model=new Model();
		$rs_model=$Model->getOne($model_id);
		
		$form_url['action']='add';
		$form=new Baogg_View_Extform(array("url"=>$form_url,"height"=>$rs_model[0]['form_height'],"width"=>600));
	
		$form->addItem(0,array("name"=>"model_id",'xtype'=>'hidden','value'=>$model_id));
		$count=count((array)$rs);
		$column_count=floor($count / 3);
		$column_count_extra= $count % 3;
		$column_pos=array(0,0,0);
		$field_items=array();
		for($i=0;$i<3;$i++){			
			$column_pos[$i]+=($i>0?$column_pos[$i-1]:0)+$column_count + ($column_count_extra>$i?1:0);
			//$field_items[$i]=array("columnWidth"=>"0.3","layout"=>"form");
		}
		//echo '<pre>';print_r($column_pos);var_dump($count);exit;
		$pos=0;
		foreach((array)$rs as $k=>$v){
			if($k>=$column_pos[$pos]){
				$pos++;
			}			
			$item=array("xtype"=>$v['field_view'],
				"fieldLabel"=>$v['show_name'],
				"name"=> $v['field_name'],
				"anchor"=> '95%'
			);
			//add user group id filter for user list
			/*if( $v['field_name']=="user_id"){
				
				
				if($user_id){
					$v['field_options'].=" and user_id='{$user_id}' ";
					$item['value']=(int)$user_id;
				}else{
					 if(!$_SESSION['admin']['user_group_role']['user_group_id']){	  		
					  		$v['field_options'].=" and user_id='{$_SESSION['admin']['user']['user_id']}' ";
					  		$item['value']=$_SESSION['admin']['user']['user_id'];
					  }else{
						   $arr_group_ids=(array)$_SESSION['admin']['user_group_role']['user_group_id'];
							 $arr_group_ids=implode(",",$arr_group_ids);
					  		$v['field_options'].=" and user_group_id in ({$arr_group_ids})";
					  }
					 
				}				
				 
			}*/
			
			
			
			
			
			if(in_array($v['field_view'],array('combo','radiogroup','checkboxgroup'))){
				$item_option=ModelTable::handleFieldOptions($v['field_options'],$params);							
				$item=array_merge($item,$item_option);
			
			}else if($v['field_view']=='htmleditor'){
				$item['height']='300';
				$item['width']='600';
				unset($item['anchor']);
			}
			$form->addItem($pos,$item);
		}
		$form->addExistButtons(array('-','save_grid','save_new','save','-','search','-','cancel'));//,'config','config'
					
		$this->view->form=$form;
		//	$json_field_items=Zend_Json::encode($field_items);
		
		
		//$cm['sub_table']=array("hidden"=>true,"cmType"=>Baogg_View_Extgrid::CMTYPE_SUBTABLE) ; //Baogg_View_Extgrid::;
		
		
		
		//$this->view->form_url=BAOGG_BASE_URL."mall/userinfo/save/model_id/{$model_id}";
		$this->view->LANG=Zend_Json::encode($LANG);
		$this->view->grid = $grid->render();
		
		
		

	}

	/**
	 * The data action
	 */
	function dataAction() {	

	    $post=$this->_request->getPost ();
	    $params=$this->getRequest()->getParams();
	    //echo '<pre>';print_r($_SESSION);exit;
	     $where=array();$order=array();$limit=array();
	     
	    //filter group id
	    $user=new User();
	    if(isset($params['user_id']) && is_numeric($params['user_id'])){
			$where[$this->userinfo->getName().'.user_id']=(int)$params['user_id'];
		}else{
			$User=new User();
			if(!$User->isAdmin() && (!$_SESSION['admin']['user_group_role']['user_group_id'] || $_SESSION['admin']['user_group_role']['user_group_id']==array(0))){	  		
			  		$where[$this->userinfo->getName().'.user_id']=(int)$_SESSION['admin']['user']['user_id'];
			  		
			  }else{
			  		$where['user_group_id']=(array)$_SESSION['admin']['user_group_role']['user_group_id'];
			  }
			
		}
		
		

	   
	   $post=$this->model->filterForm($post);
	   foreach((array)$post as $k=>$v){
	       if($k=="start" || $k=="limit"){
	           $limit[$k]=$v;
	       }else if($k=="sort" || $k=="dir"){
	           $order[$k]=$v;
	       }else{
	           if($k=="user_id"  ){
	           	    $k=BAOGG_MDB_PREFIX."user.".$k;	           		
	               if($v && is_numeric($v)){	               
	                   $v=(int)$v;
	                   $where[$k]=$v;
	               }else if($this->userinfo->is_query_value($v)){
	               		$where['user_name']=$v;
	               }
	           }else if($v!=""){
	               $where[$k]=$v;
	           }	           
	       }
	   }
	   //echo __FILE__.__LINE__.'<pre>';print_r($where);exit;
	   $data=$this->userinfo->getModelList($where,$order,$limit);
	   $rs_count=$this->userinfo->getModelList($where,NULL,NULL,array("main"=>"count(*) as cnt","ext"=>""));
	   
	   $model_id=$this->getRequest()->getParam('model_id');
	   Zend_Loader::loadClass('ModelField');
	   $modelField=new ModelField();
	   $rs=$modelField->getList(array("model_id"=>(int)$model_id,"state"=>1),array("sort"=>"ordering","dir"=>"asc"));
	   $convert=array();
	   $converter=array();
	   foreach((array)$rs as $k=>$v){	   		
	   		if($v['field_view']=='fileuploadfield'){
	   			$options=array("field_view"=>"fileuploadfield");
	   			/*$where_attachment=array();
	   			$where_attachment['module']=$params['module'];
	   			$where_attachment['controller']=$params['controller'];
	   			$Attachment=new Attachment();
	   			$rs_attachment=$Attachment->getList($where_attachment);
	   			foreach($rs_attachment as $row_attachment){

	   				$json_param=Zend_Json::decode($row_attachment['params']);
	   				if(is_array($json_param) && @$json_param['model_id']=$params['model_id']){
	   					$rs_options['source'][]=array($row_attachment['attachment_id'],'<a href="'.BAOGG_UPLOAD_URL.'upload/'.$row_attachment['module'].'/'.$row_attachment['controller'].'/'.$row_attachment['real_name'].'.'.$row_attachment['suffix'].'">'. $row_attachment['file_name'].'.'.$row_attachment['suffix'].'</a>');
	   				}
	   			}*/
	   			//echo '<pre>';print_r($rs_options);exit;
	   		}else if(in_array($v['field_view'],array('combo','radiogroup','checkboxgroup'))){
	   			
	   			$options=Zend_Json::decode($v['field_options']);
	   			$options=isset($options['grid'])?$options['grid']:$options['form'];
		   		/*$rs_options= ModelTable::handleFieldOptions($v['field_options'],array_merge((array)$v,(array)$params),"grid");
		   		if(!$rs_options || !in_array($v['field_view'],array('combo','radiogroup','checkboxgroup'))){
		   			continue;
		   		}*/
	   		}else{
	   			continue;
	   		}
	   		
	   		@$converter[$v['field_name']]=$options;
	   		
	   }
	   //echo '<pre>';print_r($converter);exit;
	   foreach((array)$data as $k=>$v){
	   		foreach($converter as $field=>$opt){
	   			$rs_opt=ModelTable::handleFieldOptions($opt,array_merge($params,$v),"grid");
	   			@$data[$k][$field.'2']=$rs_opt?$rs_opt[@$v[$field]]:"";	   			
	   		}
	   }
	  
	 /* echo '<pre>';
	  var_dump($data);
	  echo   Baogg_Db::debugDb(Zend_Registry::get('db'));
	  exit;*/
		
	  // echo Baogg_Db::debugDb(Zend_Registry::get("db"));exit;
	   echo  Zend_Json::encode(array("count"=>$rs_count[0]['cnt'],"data"=>$data));
	   $this->_helper->viewRenderer->setNoRender ();
	}

	
	/**
	 * The add action
	 */
	function addAction(){	
		
		$this->saveAction();
		
	}
	
	/**
	 * The edit action
	 */
	function editAction() {
		$this->saveAction();
	}

	/**
	 * The delete action
	 */
	function deleteAction() {
        
	    $ret=array("success"=>false,"msg"=>"delete_fail");
	    $id = Baogg_Controller_Action::_getParam ( 'ids' );
		
		$flag=$this->model->_delete($id);

		//echo Baogg_Db::debugDb(Zend_Registry::get('db'));
		
		if ($flag){
			$ret['success'] = true;
			$ret["msg"]="delete_ok";
		}
		
		echo Baogg_Language::outputResult($ret);
		 $this->_helper->viewRenderer->setNoRender ();
		
		
	}
	
	function removeAction(){
		$this->deleteAction();
	}
	
	/**
	 * The save action
	 */
	function saveAction() {
		//global $LANG;
	
	    $ret=array("success"=>false,"msg"=>"save_fail");
	    
	    //check form
		if (!$this->_request->isPost ())
		{
		   echo Baogg_Language::outputResult($ret);
		   exit;
		}
		
		if($_FILES){
			$Attachment=new Attachment();
			$ret=$Attachment->upload($this->getRequest()->getParams());
			if(isset($ret['flag']) && !$ret['flag']){
				echo Baogg_Language::outputResult($ret);
				exit; 
			}
		}
		
		$formData = $this->_request->getPost ();
		$params=$this->getRequest()->getParams();
		
		if(!$formData)
		{
		   echo Baogg_Language::outputResult($ret);
		   exit;     
		}
		
		
		
		 //filter group id
	    $user=new User();
	    /*if(!$user->isAdmin())
	    {
	    	
		    $permission=new Permission();
		    $arr_group_id=$permission->check('model','model_id',$params['model_id'],$_SESSION['admin']['user_group_role']['role_id'],$params['action']);        	
	        if($arr_group_id!==false){
	        	$is_include_self=in_array("0",$arr_group_id);
				$arr_group_id=array_filter($arr_group_id);		
				Zend_Loader::loadClass('UserGroup');
				$userGroup=new UserGroup();
				$arr_group_id=$userGroup->getWithChildIds($arr_group_id);			        	
	        }	       
	       // echo '<pre>';var_dump($formData['user_id']);echo __FILE__;exit;
	        $rs_user=$user->getOne($formData['user_id']);
	        if($arr_group_id && in_array($rs_user[0]['user_group_id'],$arr_group_id) || $is_include_self && $formData['user_id']==$_SESSION['admin']['user']['user_id']){
	        	
	        }else{
	        	echo  Zend_Json::encode(array("count"=>0,"data"=>array()));
	        	exit;
	        }	
	    }	*/
		
		$arr_model=$this->model->filterForm($formData);
		
		
		// echo '<pre>';print_r($arr);print_r($arr_model);exit;
		$rs = $this->model->getSame($arr_model);
		if($params['action']=='edit'){
			//update record
			//$permission_type = 2;
			//echo '<pre>';print_r($rs);print_r($arr_model);exit;
			if(!$rs ||  (count($rs)==1 &&  $rs[0] == $arr_model["id"] )){
			    $this->model->update($arr_model, "id={$arr_model['id']}");
			    $ret['success'] = true;				
				$ret['msg'] = "save_ok";			
			}else{
				$ret['msg'] = "exist_same_record";
			}
			
		}else{
			//insert record
			//$permission_type = 1;			
			if($rs){				
				$ret['msg'] = "exist_same_record";
			}else{
			    unset($arr_model["id"]);
				$ret['success'] =$this->model->insert($arr_model)?true:false;
				
				$ret['msg'] = "add_ok";
			}
		}
				
		echo Baogg_Language::outputResult($ret);
		//echo Baogg_Db::debugDb(Zend_Registry::get('db'));exit;
		$this->_helper->viewRenderer->setNoRender ();
		
		
	}
	


}
